#!/bin/bash

# Default installation path
INSTALL_PATH="/opt/hygon"

SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
SFTP_TOOL="$SCRIPT_DIR/../../tools/sftp"

echo "Installing hag to $INSTALL_PATH/bin"
mkdir -p -- "$INSTALL_PATH/bin" || { 
    echo "Failed to create directory: $INSTALL_PATH/bin" >&2
    exit 1
}

# Download the hag file using the sftp.sh script
if [ ! -f "$SFTP_TOOL" ]; then
    if [ ! -f ./sftp ]; then
        wget https://gitee.com/anolis/hygon-devkit/raw/master/tools/sftp
    fi
    chmod +x sftp
    ./sftp download "/hygon-devkit/4.0/2025-01-01/bin/hag" "$INSTALL_PATH/bin/hag"
else
    "$SFTP_TOOL" download "/hygon-devkit/4.0/2025-01-01/bin/hag" "$INSTALL_PATH/bin/hag"
fi

if [ $? -ne 0 ]; then
    echo "Failed to download hag file."
    exit 1
fi

# Set executable permission for the hag binary
chmod +x "$INSTALL_PATH/bin/hag"
echo "hag installed to $INSTALL_PATH/bin successfully!"